package com.ml.mall.utils;

import com.alibaba.fastjson.JSON;
import com.ml.mall.consts.MailConstants;
import com.ml.mall.enums.CommonEnum;
import com.ml.mall.exception.BizException;
import com.ml.mall.model.MailMessage;
import lombok.extern.slf4j.Slf4j;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.Set;

/**
 * Created by kyyang on 2021/7/27 22:12
 */
@Slf4j
public class MailUtils {


    /**
     * 发送邮件需身份认证
     */
    private static Boolean isAuth ;

    /**
     * 发送的邮件类型主机域名
     */
    private static  String smtpHost ;

    /**
     * 发件人账号1
     */
    private static  String infoMailUser ;

    /**
     * 发件人账号2
     */
    private static  String orderMailUser ;

    /**
     * 访问smtp的密码
     */
    private static  String mailPwd ;


//国内
//    static {
//        isAuth = true;
//        smtpHost = "smtp.163.com";
//        infoMailUser = "azsm168@163.com";
//        orderMailUser = "azsm168@163.com";
//        mailPwd = "MNKUIIUDQOFJFTQU";
//    }

//马来
    static {
        isAuth = true;
        smtpHost = "titan.sfdns.net";
        infoMailUser = "wecare@airenaprocure.com";
        orderMailUser = "order@airenaprocure.com";
        mailPwd = "89ol.>LO(*";
    }

    public static void main(String[] args) {
        MailMessage message = new MailMessage();
        message.setContent("测试内容");
        message.setSubject("测试主题");
        message.setReceiverEmail("daizhangheng@gmail.com");
        sendMail(message,0);
    }


    public static void doSendEmail1(MailMessage message){
        if(message.getReceiverEmailSet()!=null&&message.getReceiverEmailSet().size()>0){
            Set<String> receiverEmailSet = message.getReceiverEmailSet();
            receiverEmailSet.stream().forEach(m->{
                message.setReceiverEmail(m);
                sendMail(message, message.getInformType());
            });
        }else{
            sendMail(message, message.getInformType());
        }
    }
    public static void doSendEmail2(MailMessage message){
        if(message.getReceiverEmailSet()!=null&&message.getReceiverEmailSet().size()>0){
            Set<String> receiverEmailSet = message.getReceiverEmailSet();
            receiverEmailSet.stream().forEach(m->{
                message.setReceiverEmail(m);
                sendMail(message, message.getInformType());
            });
        }else{
            sendMail(message, message.getInformType());
        }
    }


    private static void sendMail(MailMessage message, Integer type) {
        // 配置发送邮件的环境属性
        final Properties props = new Properties();
        // 表示SMTP发送邮件，需要进行身份验证
        props.put(MailConstants.MAIL_SMTP_AUTH, isAuth);
        props.put(MailConstants.MAIL_SMTP_HOST, smtpHost);
        // 发件人的账号
        if(MailConstants.INFO_TYPE.equals(type)){
            props.put(MailConstants.MAIL_USER, infoMailUser);
        }else {
            props.put(MailConstants.MAIL_USER, orderMailUser);
        }
        // 访问SMTP服务时需要提供的密码
        props.put(MailConstants.MAIL_PASSWORD, mailPwd);
        // 构建授权信息，用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty(MailConstants.MAIL_USER);
                String password = props.getProperty(MailConstants.MAIL_PASSWORD);
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息，创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // 创建邮件消息
        MimeMessage mimeMessage = new MimeMessage(mailSession);
        try {
            // 设置发件人
            InternetAddress form = new InternetAddress(props.getProperty(MailConstants.MAIL_USER));
            mimeMessage.setFrom(form);
            // 设置收件人
            InternetAddress to = new InternetAddress(message.getReceiverEmail());
            mimeMessage.setRecipient(javax.mail.Message.RecipientType.TO, to);
            // 构建消息
            mimeMessage.setSubject(message.getSubject());
            mimeMessage.setContent(message.getContent(),"text/html;charset=UTF-8");
            // 发送邮件
            Transport.send(mimeMessage);
            Thread.sleep(1000);
            log.info("成功发送,邮件内容:[{}]", message.getReceiverEmail());
        } catch (Exception e) {
//            log.error("邮件发送失败,邮件内容:[{}]", JSON.toJSONString(message));
            log.error("邮件失败原因：[{}]",e);
            throw new BizException(CommonEnum.MAIL_SEND_ERROR);
        }
    }

}
